// pub mod opcua_webapi; // 暂时注释掉，专注于基础Swagger功能
pub mod swagger;

use anyhow::Result;
use log::info;
use crate::config::Config;

pub async fn start_server(config: Config) -> Result<()> {
    info!("启动 IndustryAgent Web 服务器");
    info!("Swagger UI 地址: http://{}/swagger-ui/", config.server_address());
    info!("API 文档地址: http://{}/api-docs/openapi.json", config.server_address());

    // 创建简单的健康检查端点用于测试
    use warp::{Filter, Reply};
    use std::sync::Arc;

    // 健康检查端点
    let health = warp::path("health")
        .and(warp::get())
        .map(|| {
            warp::reply::json(&serde_json::json!({
                "status": "healthy",
                "service": "IndustryAgent",
                "version": "1.0.0"
            }))
        });

    // 版本信息端点
    let version = warp::path("version")
        .and(warp::get())
        .map(|| {
            warp::reply::json(&serde_json::json!({
                "api_version": "1.0.0",
                "opcua_version": "1.04",
                "build_time": option_env!("BUILD_TIME").unwrap_or("unknown"),
                "git_commit": option_env!("GIT_COMMIT").unwrap_or("unknown"),
                "rust_version": option_env!("RUST_VERSION").unwrap_or("unknown"),
            }))
        });

    // 从swagger模块获取路由
    let swagger_routes = swagger::build_swagger_routes();

    // 组合所有路由
    let routes = health
        .or(version)
        .or(swagger_routes)
        .with(warp::cors().allow_any_origin());

    // 启动服务器
    let addr: std::net::SocketAddr = config.server_address().parse()
        .expect("无效的服务器地址");

    info!("HTTP 服务器启动在: {}", config.server_address());
    warp::serve(routes)
        .run(addr)
        .await;

    Ok(())
}